<?php
/**
 * 混合sku模型
 * (model)
 */
namespace App\Models\Product;

use Encore\Admin\Traits\Resizable;
use Illuminate\Database\Eloquent\Model;
class ProductMixSku extends Model
{
    use Resizable;

    protected $table = 'product_sku';

    protected $guarded = [];

    //默认会基于当前模型名(ProductSku)来决定外键名称：模型名_id
    public function packing(){
        return $this->hasOne(ProductPacking::class,'psku_id');
    }

    public function packing_box(){
        return $this->hasMany(ProductPackingBox::class,'psku_id');
    }

    public function image(){
        return $this->hasOne(ProductImage::class,'psku_id');
    }

    public function classify(){
        return $this->belongsTo(ProductClassify::class,'classify_id');
    }

    /**
     * 字符格式转数组格式 SKU_CODE作为KEY
     * @param $mixRuleStr
     * @return array
     */
    private static function _mixRuleArrCodeAsKey($mixRuleStr){
        $items = $mixRuleStr ? explode(',',$mixRuleStr) : [];
        $arr = [];
        foreach ($items as $item){
            $_temp = explode('-',$item);
            $arr[$_temp[0]] = intval($_temp[1]);
        }
        return $arr;
    }

    /**
     * 字符格式转数组格式 ID作为KEY
     * @param $mixRuleStr
     * @return array
     */
    public static function _mixRuleArrIDAsKey($mixRuleStr){
        $arr = self::_mixRuleArrCodeAsKey($mixRuleStr);
        $re = [];
        foreach ($arr as $key => $value){
            $pSkuId = ProductSku::getValueByCode($key,'id');
            $re[$pSkuId] = $value;
        }
        return $re;
    }

    /**
     * 获取主产品和倍数
     * @param $mixRuleStr
     * @return array
     */
    public static function getMpSku($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        foreach ($arr as $key => $item) {
            return ['m_psku_id' => $key,'m_num' => $item];
        }
        return ['m_psku_id' => null, 'm_num' => null];
    }

    /**
     * 检查组合产品规则：必须都是普通产品且未删除
     * @param $mixRuleStr
     * @return bool
     */
    public static function checkMixRule($mixRuleStr){
        $mixRuleArr = self::_mixRuleArrCodeAsKey($mixRuleStr);
        $keys = array_keys($mixRuleArr);
        $count = self::query()->whereIn('psku_code',$keys)->where('is_mix',0)->count();
        return $count != count($keys) ? false : true;
    }

    /**
     * 获取生产周期   备货提货
     * @param $mixRuleStr
     * @return int
     */
    public static function getMixSkuPuCycle($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        $puCycle = ProductSupplier::query()
            ->whereIn('psku_id',array_keys($arr))
            ->where('status',1)
            ->max('purchase_cycle');
        return $puCycle ?: 0;
    }

    /**
     * 获取采购单价  发货金额
     * @param $mixRuleStr
     * @return float
     */
    public static function getMixSkuPuPrice($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        $puSupplier = ProductSupplier::query()
            ->select('psku_id','unit_price')
            ->whereIn('psku_id',array_keys($arr))
            ->where('status',1)
            ->get();
        $puPrice = 0;
        foreach ($puSupplier as $v){
            if(!array_key_exists($v->psku_id,$arr))continue;
            $puPrice += $v->unit_price * $arr[$v->psku_id];
        }
        return round($puPrice,3);
    }

    /**
     * 获取采购单价 不含税单价
     * @param $mixRuleStr
     * @return float|int
     */
    public static function getMixSkuPuPriceNoTax($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        $puSupplier = ProductSupplier::query()
            ->select('psku_id','unit_price')
            ->whereIn('psku_id',array_keys($arr))
            ->where('status',1)
            ->get();
        $puPriceNoTax = 0;
        foreach ($puSupplier as $v){
            if(!array_key_exists($v->psku_id,$arr))continue;
            $puPriceNoTax += ProductSku::tax($v->unit_price,$v->supplier->tax ?? 0,$arr[$v->psku_id]);
        }
        return round($puPriceNoTax,3);
    }

    /**
     * 获取生产周期和采购单价
     * @param $mixRuleStr
     * @return array
     */
    public static function getMixSkuPuCycleAndPuPrice($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        $puSupplier = ProductSupplier::query()
            ->select('psku_id','supplier_price','unit_price','purchase_cycle')
            ->whereIn('psku_id',array_keys($arr))
            ->where('status',1)
            ->get();
        $suPrice = 0;
        $puPrice = 0;
        $puCycle = 0;
        foreach ($puSupplier as $v){
            if(!array_key_exists($v->psku_id,$arr))continue;
            if($v->purchase_cycle > $puCycle)$puCycle = $v->purchase_cycle;
            $suPrice += $v->supplier_price * $arr[$v->psku_id];
            $puPrice += $v->unit_price * $arr[$v->psku_id];
        }
        return ['purchase_cycle' => $puCycle,'supplier_price' => round($suPrice,3),'unit_price' => round($puPrice,3)];
    }

    /**
     * 获取生产周期，采购单价和不含税单价
     * @param $mixRuleStr
     * @return array
     */
    public static function getMixSkuPuCycleAndPuPriceAndNoTax($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        $puSupplier = ProductSupplier::query()
            ->select('psku_id','supplier_price','unit_price','purchase_cycle')
            ->whereIn('psku_id',array_keys($arr))
            ->where('status',1)
            ->get();
        $suPrice = 0;
        $puPrice = 0;
        $puPriceNoTax = 0;
        $puCycle = 0;
        foreach ($puSupplier as $v){
            if(!array_key_exists($v->psku_id,$arr))continue;
            if($v->purchase_cycle > $puCycle)$puCycle = $v->purchase_cycle;
            $suPrice += $v->supplier_price * $arr[$v->psku_id];
            $puPrice += $v->unit_price * $arr[$v->psku_id];
            $puPriceNoTax += ProductSku::tax($v->unit_price,$v->supplier->tax ?? 0,$arr[$v->psku_id]);
        }
        return ['purchase_cycle' => $puCycle,'supplier_price' => round($suPrice,3),'unit_price' => round($puPrice,3),'unit_price_no_tax' => round($puPriceNoTax,3)];
    }

    /**
     * 获取关联SKU
     * @param $mixRuleStr
     * @return array
     */
    public static function relatedSkuInfo($mixRuleStr){
        return array_map(function ($item){
            $_temp = explode('-',$item);
            $pSkuCode = $_temp[0];
            $num = $_temp[1];
            $pInfo = self::query()->where('psku_code',$pSkuCode)->select('id','psku_cn','psku_status')->first();
            $re = [];
            if($pInfo){
                $re['psku_id'] = $pInfo->id;
                $re['psku_code'] = $pSkuCode;
                $re['psku_cn'] = $pInfo->psku_cn;
                $re['psku_status'] = ProductSku::$_pSkuStatus[$pInfo->psku_status];
                $re['num'] = $num;
            }
            return $re;
        },explode(',',$mixRuleStr));
    }

    /**
     * 获取关联产品的采购供应商信息
     * @param $mixRuleStr
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function relatedSkuSuppliers($mixRuleStr){
        $arr = self::_mixRuleArrIDAsKey($mixRuleStr);
        return ProductSupplier::query()
            ->join('b_supplier', 'b_supplier.id', '=', 'product_supplier.supplier_id')
            ->select('b_supplier.code','b_supplier.name','product_supplier.*')
            ->whereIn('psku_id',array_keys($arr))
            ->get();
    }
}
